package com.star.modules.sys.task;

import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.mapper.BeanMapper;
import com.jeesite.common.web.http.HttpClientUtils;
import com.jeesite.modules.sys.utils.ConfigUtils;
import com.jeesite.modules.sys.utils.DictUtils;
import com.star.modules.sys.entity.ShHouse;
import com.star.modules.sys.entity.ShInfo;
import com.star.modules.sys.enums.DictEnum;
import com.star.modules.sys.service.IndexService;
import com.star.modules.sys.service.ShHouseService;
import com.star.modules.sys.service.ShInfoService;
import com.star.modules.sys.util.FreeMarkertUtil;
import com.star.modules.sys.vo.ArticleInfoVo;
import com.star.modules.sys.vo.HouseDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class HtmlGenTask {

    @Autowired
    private ShInfoService shInfoService;

    @Autowired
    private ShHouseService shHouseService;

    private final static String TEMPLATE_FTL = HtmlGenTask.class.getClassLoader().getResource("template").getPath();

    private final static String FTL_INFO = "info.ftl";

    private final static String FTL_HOUSE = "details.ftl";

    private final static String SAVE_PATH = ConfigUtils.getConfig("static.html.dir").getConfigValue();

    private final static String PUSH_BAIDU_URL = "http://data.zz.baidu.com/urls?site=www.starsea-house.com&token=ID2WlQM2qdfrEy1v";

    private final static String STARSEA_URL_PRE = "http://www.starsea-house.com/";

    /**
     * 生成文章html
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void converInfo() {
        Date currentTime = getUpdateTime();
        ShInfo shInfo = new ShInfo();
        shInfo.setStatus(ShInfo.STATUS_NORMAL);
        shInfo.setUpdateDate_gte(currentTime);
        List<ShInfo> shInfoList = shInfoService.findList(shInfo);
        FreeMarkertUtil freemkInfo = new FreeMarkertUtil(TEMPLATE_FTL, FTL_INFO);
        FreeMarkertUtil freemkHouse = new FreeMarkertUtil(TEMPLATE_FTL, FTL_HOUSE);
        Map<String, Object> root = MapUtils.newHashMap();
        Writer out = new OutputStreamWriter(System.out);
        ShHouse shHouse = new ShHouse();
        shHouse.setStatus(ShHouse.STATUS_NORMAL);
        shHouse.setUpdateDate_gte(currentTime);
        List<ShHouse> shHouseList = shHouseService.findList(shHouse);
        try {
            shInfoList.forEach(info -> {
                ArticleInfoVo articleInfoVo = BeanMapper.map(info, ArticleInfoVo.class);
                articleInfoVo.setMenuColStr(DictUtils.getDictLabel(DictEnum.INFO_TYPE.getCode()
                        , info.getMenuCol() + "", "false"));
                root.put("info", articleInfoVo);
                freemkInfo.processTemplate(root, out, SAVE_PATH, info.getId() + ".html");
                pushBaidu(info.getId());
            });
            shHouseList.forEach(house -> {
                HouseDetailVo vo = BeanMapper.map(house, HouseDetailVo.class);
                vo.setPropertyTypeStr(DictUtils.getDictLabel(DictEnum.PROPERTY_TYPE.getCode()
                        , vo.getPropertyType() + "", IndexService.DEFAULT_LABEL));
                vo.setLandRightsStr(DictUtils.getDictLabel(DictEnum.LAND_RIGHTS.getCode()
                        , vo.getLandRights() + "", IndexService.DEFAULT_LABEL));
                vo.setCurrentStatusStr(DictUtils.getDictLabel(DictEnum.CURRENT_STATUS.getCode()
                        , vo.getCurrentStatus() + "", IndexService.DEFAULT_LABEL));
                vo.setBuildConstructionStr(DictUtils.getDictLabel(DictEnum.BUILD_CONSTRUCTION.getCode()
                        , vo.getBuildConstruction() + "", IndexService.DEFAULT_LABEL));
                vo.setUseConditionStr(DictUtils.getDictLabel(DictEnum.USE_CONDITION.getCode()
                        , vo.getUseCondition() + "", IndexService.DEFAULT_LABEL));
                root.put("house", vo);
                freemkHouse.processTemplate(root, out, SAVE_PATH, house.getId() + ".html");
                pushBaidu(house.getId());
            });
            shInfoList = null;
            shHouseList = null;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        upDateSync();
    }

    /**
     * 获取更新时间
     *
     * @return
     */
    public Date getUpdateTime() {
        File file = new File(TEMPLATE_FTL + "sysnc.txt");
        PrintWriter pw = null;
        BufferedReader br = null;
        try {
            if (!file.exists()) {
                pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), true);
                pw.println(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                return new Date();
            } else {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                return DateUtils.parseDate(br.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (pw != null) {
                pw.close();
            }
        }
        return null;
    }

    /**
     * 更新同步时间
     */
    public void upDateSync() {
        PrintWriter pw = null;
        File file = new File(TEMPLATE_FTL + "sysnc.txt");
        try {
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), true);
            pw.println(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    /**
     * 推送百度
     *
     * @param id
     */
    public void pushBaidu(String id) {
        String result = HttpClientUtils.ajaxPostJson(PUSH_BAIDU_URL, STARSEA_URL_PRE + id + ".html");

    }
}
